package org.bjf.utils;

import com.google.common.io.BaseEncoding;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * RAS工具类
 * 公钥加密，私钥解密
 * 私钥签名，公钥验签
 */
public class RSAUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(RSAUtil.class);
    public static final String KEY_ALGORITHM = "RSA";
    public static final String SIGNATURE_ALGORITHM = "SHA1WithRSA";
    public static final String ENCODING = "utf-8";
    public static final String X509 = "X.509";

    /**
     * 获取私钥
     *
     * @param key
     * @return
     * @throws Exception
     */
    private static PrivateKey getPrivateKey(String key) throws Exception {
        byte[] keyBytes = Base64.decodeBase64(key.getBytes(ENCODING));
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    /**
     * 获取公钥
     *
     * @param key
     * @return
     * @throws Exception
     */
    private static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes = Base64.decodeBase64(key.getBytes(ENCODING));
        CertificateFactory certificateFactory = CertificateFactory.getInstance(X509);
        InputStream in = new ByteArrayInputStream(keyBytes);
        Certificate certificate = certificateFactory.generateCertificate(in);
        PublicKey publicKey = certificate.getPublicKey();
        return publicKey;
    }

    /**
     * 使用公钥对明文进行加密，返回BASE64编码的字符串
     *
     * @param publicKey
     * @param plainText
     * @return
     */
    public static String encrypt(String publicKey, String plainText) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            byte[] encodedKey = Base64.decodeBase64(publicKey.getBytes(ENCODING));
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            byte[] enBytes = cipher.doFinal(plainText.getBytes());
            return new String(Base64.encodeBase64(enBytes));
        } catch (Exception e) {
            LOGGER.error("rsa encrypt exception: {}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 使用私钥对明文密文进行解密
     *
     * @param privateKey
     * @param enStr
     * @return
     */
    public static String decrypt(String privateKey, String enStr) {
        try {
            PrivateKey priKey = getPrivateKey(privateKey);
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            byte[] deBytes = cipher.doFinal(Base64.decodeBase64(enStr));
            return new String(deBytes);
        } catch (Exception e) {
            LOGGER.error("rsa decrypt exception: {}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * RSA私钥签名
     *
     * @param content    待签名数据
     * @param privateKey 私钥
     * @return 签名值
     */
    public static String signByPrivateKey(String content, String privateKey) {
        try {
            PrivateKey priKey = getPrivateKey(privateKey);
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initSign(priKey);
            signature.update(content.getBytes(ENCODING));
            byte[] signed = signature.sign();
            return BaseEncoding.base64().encode(signed);
        } catch (Exception e) {
            LOGGER.error("sign error, content: {}", content, e);
        }
        return null;
    }

    /**
     * 公钥验签
     *
     * @param content
     * @param sign
     * @param publicKey
     * @return
     */
    public static boolean verifySignByPublicKey(String content, String sign, String publicKey) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            byte[] encodedKey = Base64.decodeBase64(publicKey.getBytes(ENCODING));
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));

            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initVerify(pubKey);
            signature.update(content.getBytes(ENCODING));
            return signature.verify(BaseEncoding.base64().decode(sign));

        } catch (Exception e) {
            LOGGER.error("verify sign error, content: {}, sign: {}", content, sign, e);
        }
        return false;
    }

    public static void main(String[] args) {
        String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCIba754dE4/JknFAGVLjgzmtfLrd+cvB7uTpZ+R6HC1wMVwi3PW0lef5jckgdqIuOPsh2tfGDAEG76hRwTr224s93TAXQRQJV2Q6YVqqIkgUM9xkNi/anjJM3Gf265oeOUEacZ083WYU+ZgqZ/XEochpwts5Yon66xGSunLsUHvxWVfjUNKD/Fz6YDu/km3PZsHgk+h9dDq19O9rfwpepiWsXalfX4Jk8mOgROnBPydKl7PD1XzSY4OcbQ2YfImXGxwqfxLT7GG1Pi8niKZEpJvPU4rkoqew+4mrIACR++6i22B/udG7FQp0FzEPAL+gaVGGYgSfbCMS1T7HZHeKxxAgMBAAECggEAB8ZwfW9ANEY5GEAMowriSxadC8+Z+d3CyYQTEZlVf7wvQdMyNyoVsVwGQzPTVlosq+jTxipbfTayjHZ/liOeVjNyBe+ERONwYTATzBJQcVIomeGtv3uDbh2P2Ks0jUHLrYmgA1nN1lTva2lFweZpltyZFAWzHheTpiYwFbQVqI5G175mQ+eB0wuEtMKDd6VIjaxEiQGUcEfF+hXIVMzhmQ6zN07+ZPeSJRtRSfrL85qGwqryrNIZWhfG0dpVTDlKVz9z7DMV4/JA+cBP13QT2S/Kz26/ghtSFaLaB5YOfNyJq4wOkWwrjYRzzXubnGUKrDPfpULKq5Ot5Xjo3YsC7QKBgQDVkyPCClyi0lpRLI8PYbVZ3/RRBcfV5a9ywTwFf2Jzahdys/0bdTGTAn8SbHyJlYaybDi9DggyAsEvf5OQeH6i38kThW7TcQ9GTT+F2jR2dBH+kkqFscBJqBgfyZPddr7MHadkNSu9D57sY7pT0p7qXUSOm6h5UcGlmioNw6ENGwKBgQCjh3Fo6iLiWFOx5mBfK29KpOsgqLzj+QJH3BaDYiuERVnbIpt6fRBZZPMNfCDqf5QVRZeYJ/6EMzNNYyboIJDL55RVUY+H+ufv+YsVzBam/abZ6nsk2Zbp6hAhgGheQI9G/t1T7dDFDQJ7/txCKUXKFuP1mSnA/sVhIHJl4SKBYwKBgQCDP/hin+GMAj+U0RBdwIslX1cSj73eOlfW6t+K9Vy4VsNwLyJlxGCh2o/i756dIrHzZkR8EmqA6WZ1XS5/Qz13tJUqlP6lnD5p0sEt7gn9nZkNXDPF85Wa7l1c85EWMYpRgAvFrlNhzX66AROZvb8Bgi3GgexIGjEqJxKfANExbwKBgHPXKW5xlZ6ThU5bbN9d7GuLIgizn4M6zPPMo6IUc9EyM3H5NPxzBZbd3RMrYEHdeDANaVLe2fwaLPhgCZqcHxZiiQBbU3q3MYAcXPtm5JEM1BpAcVVsUeyH4z9oMAa8YwKe3nhq2d4M1jqyEqNHi2maB4feJObTU0z3aDJlZkUTAoGAG+cTNkKQOG4g3ki/teoOv/LUSx/UYkgm6kVy7Jr//wJyBBTC8yW1QdyFCbUqzyRb38HPijki7x69ihwyy1Pp4QGKM7Yip+1FYNSAzlddeH6JsKZeC+XDiUJ5aU4C6q8yUZ/ijf20jRCshCM4W+CF2DLLmm4bDON+DbaEPk4vKcY=";
        String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiG2u+eHROPyZJxQBlS44M5rXy63fnLwe7k6WfkehwtcDFcItz1tJXn+Y3JIHaiLjj7IdrXxgwBBu+oUcE69tuLPd0wF0EUCVdkOmFaqiJIFDPcZDYv2p4yTNxn9uuaHjlBGnGdPN1mFPmYKmf1xKHIacLbOWKJ+usRkrpy7FB78VlX41DSg/xc+mA7v5Jtz2bB4JPofXQ6tfTva38KXqYlrF2pX1+CZPJjoETpwT8nSpezw9V80mODnG0NmHyJlxscKn8S0+xhtT4vJ4imRKSbz1OK5KKnsPuJqyAAkfvuottgf7nRuxUKdBcxDwC/oGlRhmIEn2wjEtU+x2R3iscQIDAQAB";

        String content = "测试内容丝丝xxxxx";

        String sign = signByPrivateKey(content, privateKey);
        String base64Encode = Base64Util.encodeURLSafe(sign);
        String base64Decode = Base64Util.decode(base64Encode);


        boolean b = verifySignByPublicKey(content, base64Decode, publicKey);

        System.out.println("b = " + b);


    }
}
